package Worker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/*
 * The WorkerDriver implements the main entry of
 * a worker, which will rebind its services to the
 * Registry server. And this is a start point of
 * worker-side.
 */
public class WorkerDriver {
	/*
	 * VOID MAIN
	 */
    public static void main(String[] args) {
    	//Custom security manager, turned off for DEMO purpose
        //System.setProperty("java.security.policy", "local.policy");
        //System.setSecurityManager(new SecurityManager());

        String workServiceName = "WorkService";
        String registryServiceName = "RegistryService";
        String statusServiceName = "StatusService";

        String password = "password";
        float cost = 0.0f;

        //Given password for security purpose
        if (args.length == 2) {
            password = args[0];
           
        } else {
            System.out.println("usage: java Worker.WorkerDriver password");
            System.exit(-1);
        }

        try {
        	cost = Float.parseFloat(args[1]);//Get given cost per unit
        	
            // get the information about the local host name
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostAddress();

            RegistryInfo registryInfo = 
            					new Worker.RegistryInfo(password, cost);
            StatusInfo statusInfo = new StatusInfo(registryInfo);
            // we create an instance of the "worker" type
            WorkerEngine workerEngine = 
            					new WorkerEngine(registryInfo, statusInfo);

            // and register it with the local registry, we can
            // only register instance with the local registry but
            // we can query any registry that is reachable through
            // the network.
            Registry registry = LocateRegistry.createRegistry(9000);

            registry.rebind("rmi:" + workServiceName, workerEngine);
            registry.rebind("rmi:" + registryServiceName, registryInfo);
            registry.rebind("rmi:" + statusServiceName, statusInfo);

            System.out.println("worker is running.. ("+hostname+")");
        }
        catch (NumberFormatException nfe){
        	System.out.println("The cost value is invalid!");
        }
        catch (Exception ex) {
            // oops something went wrong while interacting
            // with the registry
            System.out.println("Error starting the server: "+ex.getMessage());
        }
    }
}
